import Vue from 'vue'
import Router from 'vue-router'
import store from './store/index.js'
Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      component: () => import('@/views/Home/index.vue'),
      redirect: '/product',

      children: [
        {
          path: '/product',
          component: () => import('@/views/product/Product.vue'),
        },
        {
          path: '/category',
          component: () => import('@/views/category/Category.vue'),
        },
        {
          path: '/cart',
          component: () => import('@/views/cart/Cart.vue'),
          meta: {
            auth: true,
          },
        },
        {
          path: '/member',
          component: () => import('@/views/member/Member.vue'),
        },
      ],
    },
    {
      path: '/register',
      component: () => import('@/views/login/Register.vue'),
    },
    {
      path: '/login',
      component: () => import('@/views/login/Login.vue'),
    },
    {
      path: '/info',
      component: () => import('@/views/member/Info.vue'),
    },
    {
      path: '/order',
      component: () => import('@/views/order/Order.vue'),
      meta: {
        auth: true,
      },
    },
    {
      path: '/address',
      component: () => import('@/views/address/Address.vue'),
    },
    {
      path: '/addaddress',
      component: () => import('@/views/address/AddAddress.vue'),
    },
    {
      path: '/detail',
      component: () => import('@/views/detail/Detail.vue'),
      meta: {
        auth: true,
      },
    },
    {
      path: '/orderwait',
      component: () => import('@/views/order/OrderWait.vue'),
      meta: {
        auth: true,
      },
    },
    {
      path: '/set',
      component: () => import('@/views/member/Set.vue'),
      meta: {
        auth: true,
      },
    },
  ],
})
// 全局路由钩子函数 对全局有效
router.beforeEach((to, from, next) => {
  let auth = to.meta.auth
  const isLogin = store['login']
  if (auth && !isLogin) {
    // 需要登录
    store.dispatch('getUserInfo').then(response => {
      if (response.code == -1) {
        Vue.$shouldLogin.open({
          path: to.fullPath,
          backClose: !!from.matched.length,
        })
      } else {
        next()
      }
    })
    return
  } else {
    Vue.$shouldLogin.close()
  }
  next()
})
export default router
